%% AFIScript function : Calculates B1 map from AFI sequence data.
% Mathematical derivation of equations can be found in 
% Yarnykh, MRM 57:192-200 (2007).   
%
% Script inputs two images: afi1 and afi2. 'afi1' is the image acquired
% during TR1 (shortest, and first); 'afi2' is the image acquired during
% TR2=N*TR1. 'angle' is the nominal flip angle set on the scanner, and
% must be in degrees.
%
% Output is a B1 map, which values should be centered around 1.
%% Function Declaration
%
function [ b1map ] = AFIB1Map( afi1, afi2, N, NominalAngle)
%% Cast int32 images to double.
% Needed due to use of loadminc tool.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%
afi1=cast(afi1, 'double');
afi2=cast(afi2, 'double');
%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Calculate the cosine of the true flip angles.
%
r = abs(afi2./afi1);      % Same r as in Yarnykh.

cos_arg = (r*N-1)./(N-r); % Assumes TR1,2 << T1 and 1-TR1,2 ~= 1.

%% Filter out cases where r > 1.
% r should/can not be larger than one, except in the case of noise.
cos_arg = double(cos_arg).*(r<=1) + ones(size(r)).*(r>1);

%% Calculate true flip angle.
%
alpha = acos(cos_arg); %alpha is in radians

%%  Convert flip angle map to relative B1 map.
% To convert alpha to a relative factor, we divide by the nominal flip 
% angle in radians.

b1map = alpha/(NominalAngle*pi/180);

end

